package org.springblade.modules.repair.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.dto.RescueNoticeListDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.*;
import org.springblade.modules.repair.mapper.RescueNoticeMapper;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.AIRescueNoticeVO;
import org.springblade.modules.repair.vo.RescueEstateLinkmanVO;
import org.springblade.modules.repair.vo.RescueNoticeTitleVO;
import org.springblade.modules.repair.vo.rescue.RescueNoticeDetailVO;
import org.springblade.modules.repair.vo.rescue.RescueNoticeListVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Service
public class RescueNoticeServiceImpl extends BaseServiceImpl<RescueNoticeMapper, RescueNotice> implements IRescueNoticeService {

	private final ElevatorPrincipalDeptService elevatorPrincipalDeptService;

	private final BuildingContactsService buildingContactsService;

	private final IRescueNoticeAiSessionService aiNoticeSessionService;

	private final IRescueNoticeAiSessionContentService aiNoticeSessionContentService;

	private final RelationAliasService relationAliasService;

	@Override
	public IPage<RescueNoticeListVO> getNoticeListByCondition(IPage<RescueNoticeListVO> page, RescueNoticeListDTO rescueNoticeListDTO) {

		IPage<RescueNoticeListVO> noticeListByCondition = baseMapper.getNoticeListByCondition(page, rescueNoticeListDTO);
		// 数据描述处理
		List<RescueNoticeListVO> records = noticeListByCondition.getRecords();
		records.forEach(r -> {
			String eventCode = r.getEventCode();
			if(Func.isNotEmpty(eventCode)){
				r.setEventCodeDesc(RescueNoticeTypeEnum.getSourceByEventCode(eventCode));
			}
			Integer eventLevel = r.getEventLevel();
			if(Func.isNotEmpty(eventLevel)){
				r.setEventLevelDesc(RescueNoticeEventLevelEnum.getEventLevelDescByEventLevel(eventLevel));
			}
			// 工单类型及状态
			Integer typeStatus = r.getTypeStatus();
			if(Func.isNotEmpty(typeStatus)){
				r.setTypeStatusDesc(MaintainPlanContentEnum.getName(typeStatus));
				Integer status = r.getStatus();
				r.setStatusDesc(TaskStatusEnum.getTaskName(typeStatus, status));
			}
			Integer confirmType = r.getConfirmType();
			if(Func.isNotEmpty(confirmType)){
				r.setConfirmTypeDesc(RescueNoticeConfirmTypeEnum.getConfirmTypeDescByConfirmType(confirmType));
			}
			// 项目别名
			if(Func.isNotEmpty(r.getBuildingId())){
				List<RelationAlias> buildingAlias = relationAliasService.list(new LambdaQueryWrapper<RelationAlias>()
					.eq(RelationAlias::getRelationId, r.getBuildingId())
					.eq(BaseEntity::getIsDeleted, 0)
					.eq(BaseEntity::getStatus, 2)
				);
				if(Func.isNotEmpty(buildingAlias)){
					List<String> aliasList = buildingAlias.stream().map(RelationAlias::getAlias).collect(Collectors.toList());
					r.setBuildingAlias(String.join("/", aliasList));
				}
			}
			// 电梯别名
			if(Func.isNotBlank(r.getElevatorAlias())){
				r.setElevatorAlias(r.getElevatorAlias().replaceAll(",", "/"));
			}
		});

		noticeListByCondition.setRecords(records);
		return noticeListByCondition;
	}

	@Override
	public RescueNoticeDetailVO getNoticeDetailById(Long rescueNoticeId) {
		// 1. 根据告警id查询告警详情
		RescueNoticeDetailVO rescueNoticeDetailVO = baseMapper.getNoticeDetailById(rescueNoticeId);
		// 2. 补充告警详情
		if(Func.isNotEmpty(rescueNoticeDetailVO)){
			// 补充告警详情
			if(Func.isNotEmpty(rescueNoticeDetailVO.getPlanId())){
				// 工单状态描述补充
				Integer status = rescueNoticeDetailVO.getStatus();
				Integer typeStatus = rescueNoticeDetailVO.getTypeStatus();
				if(Func.isNotEmpty(status) && Func.isNotEmpty(typeStatus)){
					rescueNoticeDetailVO.setStatusDesc(TaskStatusEnum.getTaskName(typeStatus, status));
				}
			}
			String eventCode = rescueNoticeDetailVO.getEventCode();
			if(Func.isNotEmpty(eventCode)){
				rescueNoticeDetailVO.setEventCodeDesc(RescueNoticeTypeEnum.getSourceByEventCode(eventCode));
			}
			if(Func.isNotEmpty(rescueNoticeDetailVO.getIsStop())){
				if(Integer.valueOf(1).equals(rescueNoticeDetailVO.getIsStop())){
					rescueNoticeDetailVO.setIsStopDesc("正常");
				}else{
					rescueNoticeDetailVO.setIsStopDesc("停梯");
				}
			}
			// 电梯已知的情况,电梯维保组
			Long elevatorId = rescueNoticeDetailVO.getElevatorId();
			if(Func.isNotEmpty(elevatorId)){
				String principalDeptNames = elevatorPrincipalDeptService.getPrincipalDeptNames(elevatorId);
				rescueNoticeDetailVO.setPrincipalDeptNames(principalDeptNames);
			}
			// 确认状态和类型
			if(!Integer.valueOf(-1).equals(rescueNoticeDetailVO.getConfirmType())){
				rescueNoticeDetailVO.setConfirmTypeDesc(RescueNoticeConfirmTypeEnum.getConfirmTypeDescByConfirmType(rescueNoticeDetailVO.getConfirmType()));
				rescueNoticeDetailVO.setConfirmStatusDesc(Boolean.TRUE);
			}else{
				rescueNoticeDetailVO.setConfirmStatusDesc(Boolean.FALSE);
			}
			// 物业联系人信息，业务上不可能存在当前告警id不存在，以及当前告警下的项目id不存在
			RescueNotice currentNotice = this.getById(rescueNoticeId);

			Long buildingId = currentNotice.getBuildingId();
			List<BuildingContacts> contacts = buildingContactsService.list(new LambdaQueryWrapper<BuildingContacts>()
				.eq(BuildingContacts::getBuildingId, buildingId)
				.eq(BaseEntity::getIsDeleted, 0)
			);
			if(Func.isNotEmpty(contacts)){
				List<String> linkMessage = new ArrayList<>(contacts.size());
				List<RescueEstateLinkmanVO> estateLinkman = new ArrayList<>(contacts.size());
				contacts.forEach(c -> {
					RescueEstateLinkmanVO rescueEstateLinkmanVO = new RescueEstateLinkmanVO();
					String contactsName = c.getContactsName();
					String phone = c.getPhone();
					rescueEstateLinkmanVO.setUserName(contactsName);
					rescueEstateLinkmanVO.setPhone(phone);
					linkMessage.add(
						(Func.isEmpty(contactsName) ? "" : contactsName)
							+ (Func.isEmpty(phone) ? "" : phone)
							+";");
					estateLinkman.add(rescueEstateLinkmanVO);
				});
				// 将linkMessage List<String> 转成String
				String linkMessageStr = String.join(",", linkMessage);
				rescueNoticeDetailVO.setEstateLinkMessage(linkMessageStr);
				rescueNoticeDetailVO.setEstateLinkman(estateLinkman);
			}
			// 微信群AI告警类型,会话相关
			if(Func.isNotEmpty(rescueNoticeDetailVO.getEventCode())){
				if(rescueNoticeDetailVO.getEventCode().equals(RescueNoticeTypeEnum.CHAT_GROUP_AI.getEventCode())){
					AIRescueNoticeVO aiRescueNoticeVO = new AIRescueNoticeVO();
					// 会话信息
					List<RescueNoticeAiSession> sessionList = aiNoticeSessionService.list(new LambdaQueryWrapper<RescueNoticeAiSession>()
						.eq(RescueNoticeAiSession::getNoticeId, rescueNoticeId)
						.eq(BaseEntity::getIsDeleted, 0)
					);
					// 会话内容
					if(Func.isNotEmpty(sessionList)){
						RescueNoticeAiSession rescueNoticeAiSession = sessionList.get(0);
						aiRescueNoticeVO.setRescueNoticeAiSession(rescueNoticeAiSession);
						Long sessionId = rescueNoticeAiSession.getId();
						List<RescueNoticeAiSessionContent> contentList = aiNoticeSessionContentService.list(new LambdaQueryWrapper<RescueNoticeAiSessionContent>()
							.eq(BaseEntity::getIsDeleted, 0)
							.eq(RescueNoticeAiSessionContent::getAiSessionId, sessionId)
						);
						aiRescueNoticeVO.setRescueNoticeAiSessionContents(contentList);
						rescueNoticeDetailVO.setAiRescueNoticeVO(aiRescueNoticeVO);
					}
				}
			}
		}
		return rescueNoticeDetailVO;
	}

	@Override
	public List<RescueNoticeTitleVO> countWithRoles() {
		return baseMapper.countWithRolesList();
	}
}
